package com.bd.rj.frontstage.config;

import com.bd.rj.common.filters.CrosFilter;
import com.bd.rj.common.filters.PrintAllArgsFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class WebConfig {

    @Bean
    public FilterRegistrationBean<CrosFilter> crosFilter(){
        FilterRegistrationBean<CrosFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new CrosFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("crosFilter");
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean<PrintAllArgsFilter> PrintArgsfilter(){
        FilterRegistrationBean<PrintAllArgsFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new PrintAllArgsFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("PrintArgsFilter");
        filterRegistrationBean.setOrder(2);
        return filterRegistrationBean;
    }
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        //JSON Long ==> String
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
